<template>
  <Page class="bg-[#f5f7fa] min-h-screen">
    <!-- 顶部蓝色渐变背景 -->
    <!-- <view class="fixed top-0 left-0 w-full z-[3] h-[250rpx] bg-gradient-to-b from-[#2196F3] to-[#6ec6ff] rounded-b-[40rpx]"></view> -->

    <view class="max-w-[750rpx] mx-auto sticky top-0 z-[2]">
      <!-- 头部区域 -->
      <PageHeader title="工厂招聘" :showBack="true" :onlyBack="true" />
      <view
        class="bg-gradient-to-r from-[#165DFF] to-[#1890ff] sticky top-0 z-[2] text-white px-[32rpx] pt-[100rpx] pb-[20rpx] rounded-b-[32rpx] mb-[-40rpx] relative shadow-md"
      >
        <!-- 返回按钮 -->
        <SearchView @search="handleSearch" />
      </view>
    </view>

    <view
      class="flex mx-20rpx overflow-x-auto gap-x-[14rpx] py-[12rpx] mt-[60rpx] scrollbar-hide"
    >
      <view
        class="px-[28rpx] py-[10rpx] rounded-[16rpx] text-[24rpx] font-medium cursor-pointer transition-all duration-200 border border-transparent whitespace-nowrap"
        :class="
          activeFilter === 0
            ? 'bg-blue-500 text-white font-bold shadow'
            : 'bg-gray-200'
        "
        @click="handleFilterClick(0, 0)"
      >
        全部
      </view>
      <view
        v-for="(filter, index) in filters"
        :key="index"
        class="px-[28rpx] py-[10rpx] rounded-[16rpx] text-[24rpx] font-medium cursor-pointer transition-all duration-200 border border-transparent whitespace-nowrap"
        :class="
          activeFilter === index + 1
            ? 'bg-blue-500 text-white font-bold shadow'
            : 'bg-gray-200'
        "
        @click="handleFilterClick(index + 1, filter.type)"
      >
        {{ filter.name }}
      </view>
    </view>

    <!-- 吸顶搜索栏 -->
    <!-- <view class="sticky top-0 z-30 px-[32rpx] pt-[32rpx] bg-transparent">
      <SearchView v-model="searchText" placeholder="搜索职位、工厂或地点..." @search="handleSearch" />
      <view class="flex overflow-x-auto gap-x-[14rpx] py-[12rpx] scrollbar-hide">
        <view 
          v-for="(filter, index) in filters" 
          :key="index"
          class="px-[28rpx] py-[10rpx] rounded-[16rpx] text-[24rpx] font-medium cursor-pointer transition-all duration-200 border border-transparent whitespace-nowrap"
          :class="activeFilter === index ? 'bg-gradient-to-r from-[#2196F3] to-[#6ec6ff] text-white font-bold shadow border-[#2196F3]' : 'bg-[#f5f7fa] text-[#2196F3]/80'"
          @click="activeFilter = index"
        >
          {{ filter }}
        </view>
      </view>
    </view> -->

    <!-- 职位列表 -->
    <view class="pt-[20rpx] pb-[28rpx] px-[0]">
      <view class="p-[24rpx] flex flex-col gap-y-[24rpx]">
        <view
          v-for="(job, index) in jobData"
          :key="index"
          class="bg-white rounded-[24rpx] p-[32rpx] shadow-sm border border-[#f0f0f0] relative flex flex-col transition-all duration-300"
          @tap="goDetail(job.id)"
        >
          <!-- 头部 -->
          <view class="flex justify-between items-center mb-[16rpx]">
            <view
              class="text-[36rpx] font-bold text-[#222] flex-1 truncate leading-[1.3]"
              >{{ job.title }}</view
            >
            <view
              v-if="job.urgent"
              class="text-[24rpx] px-[16rpx] py-[8rpx] rounded-[16rpx] font-medium bg-[#ffebee] text-[#F44336]"
              >急聘</view
            >
          </view>
          <!-- 公司logo和信息 -->
          <view class="flex items-center mb-[12rpx]">
            <!-- <view
              class="w-[36rpx] h-[36rpx] rounded-[8rpx] bg-[#E3F2FD] flex items-center justify-center text-[#2196F3] text-[18rpx] mr-[8rpx] flex-shrink-0"
            >
              <IconFont :name="job.icon" />
            </view> -->
            <view
              class="text-[28rpx] text-[#2196F3] font-medium leading-[1.4]"
              >{{ job.company }}</view
            >
          </view>
          <!-- 描述 -->
          <view
            class="text-[28rpx] text-[#666] mb-[16rpx] leading-[1.6] line-clamp-2"
            >{{ job.desc }}</view
          >
          <!-- 元信息 -->
          <!-- 元信息（含薪资范围） -->
          <view
            class="flex justify-between text-[26rpx] text-[#666] mb-[16rpx]"
          >
            <view>
              <view class="mb-[4rpx]">地点：{{ job.location }}</view>
              <view>经验：{{ job.experience }}</view>
            </view>
            <!-- 薪资范围展示 -->
            <view class="text-right my-[2rpx]">
              <view class="text-[32rpx] font-bold text-[#FF4D4F]">
                {{ job.salary_min }} - {{ job.salary_max }}
              </view>
              <view class="text-[22rpx] text-[#999] mt-[2rpx]"> 月薪 </view>
            </view>
          </view>
          <!-- 标签 -->
          <view class="flex flex-wrap gap-x-[12rpx] gap-y-[12rpx] mb-[16rpx]">
            <view
              v-for="(tag, tIndex) in job.tags"
              :key="tIndex"
              class="text-[24rpx] px-[16rpx] py-[6rpx] bg-[#e3f2fd] rounded-[10rpx] text-[#2196F3] font-medium"
            >
              {{ tag }}
            </view>
          </view>
          <!-- 底部 -->
          <view class="flex justify-between items-center mt-[12rpx]">
            <view class="text-[24rpx] text-[#999]"
              >发布时间：{{ job.createTime }}</view
            >
            <nut-button
              class=""
              size="small"
              type="primary"
              @tap="goDetail(job.id)"
            >
              查看详情
            </nut-button>
          </view>
        </view>
      </view>
    </view>
    <!-- 加载更多按钮 -->
    <view class="flex justify-center mt-[20rpx] mb-[30rpx]">
      <nut-button
        size="normal"
        type="primary"
        :loading="isLoading"
        :disabled="isLoading || noMore"
        @click="loadMore"
        class="w-[300rpx] bg-[#2196F3] border-[#2196F3] rounded-[24rpx] py-[16rpx] text-[28rpx] font-medium shadow-sm transition-all duration-300"
      >
        {{ noMore ? "没有更多了" : "加载更多" }}
      </nut-button>
    </view>
  </Page>
</template>

<script setup lang="ts">
import { ref } from "vue";
import { IconFont } from "@nutui/icons-vue-taro";
import SearchView from "@/components/SearchView.vue";
import { post } from "@/utils/request";
import Taro from "@tarojs/taro";

export interface jobRequest {
  id: number; // 去掉可选
  // 职业标题
  title?: string;
  // 公司
  company?: string;
  // 图标
  // icon: "icon-factory";
  // 工作内容
  desc?: string;
  // 工作地点
  location?: string;
  // 工作经验
  experience?: string;
  // 最低工资
  salary_min?: string;
  // 最高工资
  salary_max?: string;
  // 标签
  tags?: string[];
  // 发布时间
  createTime?: string;
  //
  urgent?: boolean;
}

const searchText = ref("");
// 导航类别
const filters = ref<{ type: number; name: string }[]>([]);

const activeFilter = ref(0);

// 分页参数
const pageNo = ref(1); // 当前页码
const pageSize = ref(10); // 每页条数
const isLoading = ref(false); // 加载中状态
const noMore = ref(false); // 是否没有更多数据


const handleFilterClick = (index: number, type: number) => {
  activeFilter.value = index; // 更新选中的标签索引
  resetPagination(); // 重置分页
  jobRequest(type); // 根据类似请求数据
};

// 重置分页参数
const resetPagination = () => {
  pageNo.value = 1;
  jobData.value = [];
  noMore.value = false;
};

// 加载更多
const loadMore = () => {
  if (isLoading.value || noMore.value) return;
  pageNo.value++; // 页码+1
  jobRequest(activeFilter.value === 0 ? 0 : filters.value[activeFilter.value - 1].type);
};
// 测试数据
const jobs = [
  {
    title: "包装工",
    company: "南宁华盛电子厂",
    icon: "icon-factory",
    desc: "负责电子产品的包装与质检，工作轻松，环境优良，包吃住。",
    location: "南宁",
    experience: "不限",
    salary: "￥4000-6000",
    tags: ["包吃住", "长白班", "五险"],
    urgent: true,
    publishTime: "1小时前",
  },
];

// 页面数据
const jobData = ref<jobRequest[]>([]);
const searchValue = ref("");
function handleSearch(val: string) {
  // 搜索逻辑
  searchValue.value = val;
  resetPagination(); // 重置分页
  jobRequest(0);
}

const handleApply = async (id: Number) => {
  console.log("申请职位id===>", id);
  // 申请逻辑
  const res = await post("/recruitment/signUp", { id });
  console.log(res);
  if (res.code == "0") {
    Taro.showToast({ title: "提交报名成功！" });
  }
};

// 跳转详情
const goDetail = (id:number) => {
  Taro.navigateTo({
    url:`/pages-detail/post/recruit/factory-recruitment-detail?id=${id}`,
  })
}

// 渲染列表数据请求
const jobRequest = async (type: number) => {
  // 防止重复请求
  if (isLoading.value || noMore.value) {
    if (noMore.value) {
      Taro.showToast({ title: "没有更多了", icon: "none" });
    }
    return;
  }

  isLoading.value = true; // 开始加载

  try {
    const res = await post("/recruitment/all", {
      pageNo: pageNo.value,
      pageSize: pageSize.value,
      type: type,
      status: 0,
      recruitmentType: 0,
      title: searchValue.value
    });
    console.log('招聘列表===>', res);
    
    if (res.code == "0") {
      const newItems = res.data.map((item: any) => ({
        id: item.columns.id,
        title: item.columns.position_name,
        company: item.columns.corporate_name,
        location: item.columns.location,
        experience: item.columns.experience,
        salary_min: item.columns.salary_min,
        salary_max: item.columns.salary_max,
        desc: item.columns.description,
        createTime: item.columns.create_time,
        tags: item.columns.labels?.split(",") || [],
      }));
      
      // 第一页直接赋值，后续页追加数据
      if (pageNo.value === 1) {
        jobData.value = newItems;
      } else {
        jobData.value = [...jobData.value, ...newItems];
      }
      
      // 判断是否还有更多数据（当前页数据小于pageSize则说明没有更多）
      noMore.value = newItems.length < pageSize.value;
    }
  } catch (error) {
    console.error("获取招聘数据失败：", error);
    Taro.showToast({ title: "加载失败", icon: "none" });
  } finally {
    isLoading.value = false; // 结束加载
  }
};
jobRequest(0);

// 招聘类型
const jobRecruitmentType = async () => {
  const res = await post("/dictionary/recruitmentType");
  if (res.code == "0") {
    filters.value = res.data.map((item: any) => ({
      type: item.columns.id,
      name: item.columns.name,
    }));
  }
};
jobRecruitmentType();
// 招聘标签(弃用)
// const jobRecruitmentLabel = async () => {
//   const res = await post("/dictionary/recruitmentLabel");
//   // console.log("==>", res);
//   if (res.code == 0) {
//     tags.value = res.data.map((item) => ({
//       id: item.columns.id,
//       name: item.columns.name,
//     }));
//   }
// };


// jobRecruitmentLabel();
</script>
